package com.aurora.app.service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.transaction.Transactional;

import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.aurora.app.constant.PayConfig;
import com.aurora.app.dao.PayOrderDao;
import com.aurora.app.dao.ThingDao;
import com.aurora.app.dao.UserAccountDao;
import com.aurora.app.dao.UserDao;
import com.aurora.app.dao.WeixinAppTokenDao;
import com.aurora.app.entity.PayOrder;
import com.aurora.app.entity.Thing;
import com.aurora.app.entity.User;
import com.aurora.app.entity.UserAccount;
import com.aurora.app.entity.WeixinAppToken;
import com.aurora.app.enums.PayState;
import com.aurora.app.exption.NullEntityException;
import com.aurora.app.exption.WeiXinApiException;
import com.aurora.app.util.weixin.PayUtils;
import com.aurora.base.dao.BaseDao;
import com.aurora.base.dto.Order;
import com.aurora.base.dto.QueryResult;
import com.aurora.base.service.BaseService;

@Service
public class PayOrderService extends BaseService<PayOrder> {
	
	private final Logger LOG = LoggerFactory.getLogger(this.getClass());
	@Resource
	private PayOrderDao baseDao;
	@Resource
	private UserDao userDao;
	@Resource
	private ThingDao thingDao;
	@Resource
	private UserAccountDao userAccountDao;
	@Resource
	private WeixinAppTokenDao weixinAppTokenDao;

	@Override
	public BaseDao<PayOrder> getBaseDao() {
		// TODO 自动生成的方法存根
		return this.baseDao;
	}

	/**
	 * 新建一个订单（已废除，但是方法可用）
	 * @param product_id 货物订单
	 * @return 返回code_url
	 */
	@Transactional
	public String create( String product_id) {
		Thing thing = this.thingDao.find(product_id);
		if (thing == null) {
			throw new NullEntityException(
					"Thing can't not find by product_id: " + product_id);
		}
		PayOrder pay = new PayOrder();
		pay.setThing(thing);
		pay.setMoney(thing.getCost());
		//扣除10%的手续费
		pay.setToUserMoney(thing.getCost().multiply(BigDecimal.valueOf(0.9D)));
		//订单状态为预支付
		pay.setState(PayState.PRAPARE);
		//生成订单号
		pay.setOrder(UUID.randomUUID().toString().replaceAll("\\-", ""));
		
		
		// 获取code_url (模式二)
		//生成随机数
		String nonceStr = PayUtils.createNoncestr();
		//展示给用户看的
		String body = thing.getUser().getNickName()+"  的  "+thing.getTitle();
		//应付金额(分 为单位)
		String total = String.valueOf( pay.getMoney().multiply(BigDecimal.valueOf(10L)).longValue());
		//获取appid
		WeixinAppToken weixinAppToken = this.weixinAppTokenDao.list(null).get(0);
		String appId = weixinAppToken.getAppId();
		//生成签名
		String sign = PayUtils.getSign(nonceStr, pay.getOrder(), body,
				total, PayConfig.NOTIFY_URL, PayUtils.NATIVE, null,
				"127.0.0.1", appId);
		
		//发送信息和签名到微信支付系统
		Map<String, String> resultMap = PayUtils.getResultMap(nonceStr, pay.getOrder(), body, total,
						PayUtils.NATIVE, null,"127.0.0.1", sign, appId);
		String code_url = "";
		//获取code_url
		if(resultMap.get("return_code").equals("SUCCESS") && resultMap.get("result_code").equals("SUCCESS")){
			code_url =  resultMap.get("code_url");
		}else{
			throw new WeiXinApiException("统一下单api调用异常");
		}
		pay.setTip("生成二维码");
		this.baseDao.persist(pay);
		
		return code_url;
	}

	/**
	 * 模式二生成订单 非线上支付
	 * @param thingId
	 * @param user 支付者
	 */
	@Transactional
	public void create2(Thing thing,User user){
		PayOrder payOrder = this.baseDao.find("o.thing = ?",thing);
		if(payOrder==null){
			payOrder = new PayOrder();
			payOrder.setMoney(thing.getCost());
			payOrder.setOrder(UUID.randomUUID().toString());
			payOrder.setState(PayState.PRAPARE);
			payOrder.setThing(thing);
			payOrder.setToUserMoney(thing.getCost());
			payOrder.setUser(user);
			this.baseDao.persist(payOrder);
		}
	}
	
	/**
	 * 获取用户交易成功的单数
	 * 
	 * @param userId
	 * @return
	 */
	public long getSuccessCount(String userId) {
		return this.baseDao.getCount(
				"o.isDelete = 0 and o.thing.user.id = ? and o.state = ?", userId,PayState.SUCCESS);
	}

	/**
	 * 判断用户是否首单
	 * 
	 * @param userId
	 * @return
	 */
	public Boolean isFirst(String userId) {
		List<PayOrder> list = this.baseDao.list(
				"o.isDelete = 0 and o.user.id = ? and o.state = ?", userId,PayState.SUCCESS);
		return list.isEmpty();
	}

	/**
	 * 获取用户卖出的东东
	 * 
	 * @param request
	 * @param userId
	 * @return
	 */
	public List<PayOrder> getSellByUserWithPages(HttpServletRequest request,
			String userId) {
		Order order = new Order();
		order.put("createTime", Order.DESC);
		QueryResult<PayOrder> res = this.baseDao.query(request, order,
				"o.state = ? and o.isDelete = 0 and o.thing.user.id = ? ",PayState.SUCCESS, userId);
		request.setAttribute("count", res.getCount());
		return res.getResults();
	}

	/**
	 * 获取用户买入的东东
	 * 
	 * @param request
	 * @param userId
	 * @return
	 */
	public List<PayOrder> getBugByUserWithPages(HttpServletRequest request,
			String userId) {
		Order order = new Order();
		order.put("createTime", Order.DESC);
		QueryResult<PayOrder> res = this.baseDao.query(request, order,
				"o.state = 1 and o.isDelete = 0 and o.user.id = ? ",
				userId);
		request.setAttribute("count", res.getCount());
		return res.getResults();
	}

	
	public PayOrder getByThing(String thingId){
		return this.baseDao.find("o.thing.id = ?",thingId);
	}
}
